package com.ruoyi.common.utils.sms;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.QuerySendDetailsRequest;
import com.aliyun.dysmsapi20170525.models.QuerySendDetailsResponse;
import com.aliyun.dysmsapi20170525.models.QuerySendDetailsResponseBody;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.lang.reflect.Constructor;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @Author luobo
 * @Date 2021/8/9 11:03
 * @Describetion 短信处理工具类
 */
@Component
public class SmsUtil {
    private static final Logger log = LoggerFactory.getLogger(SmsUtil.class);
    private static final String REGION = "ap-guangzhou";
    @Autowired
    private Environment env;

    //----------------------------------------------------------------腾讯云----------------------------------------------------------------
    // https://cloud.tencent.com/developer/article/1551304?from=article.detail.1778011
    public void sendTencentSms(String templateId, String[] phones, String [] templateParam) {
        sendTencentSms(env.getProperty("sms.tencent.appId"), env.getProperty("sms.tencent.secretId"), env.getProperty("sms.tencent.secretKey"), env.getProperty("sms.tencent.sign"), templateId, phones, templateParam);
    }
    public void sendTencentSms(String appId, String secretId, String secretKey, String sgin, String templateId, String[] phones, String[] templateParam) {
        try {
            if (null == phones || phones.length == 0) {
                //throw new Exception("手机号不能为空！");
                return;
            }
            for(int i=0; i<phones.length; i++){ //因腾讯云短信在手机号前面必须加+86，此处统一处理
                phones[i] = "+86" + phones[i];
            }
            com.tencentcloudapi.sms.v20190711.models.SendSmsRequest sendSmsRequest = new com.tencentcloudapi.sms.v20190711.models.SendSmsRequest();
            sendSmsRequest.setSmsSdkAppid(appId); //appId ,见《创建应用》小节
            sendSmsRequest.setSign(sgin); //签名内容，不是填签名id,见《创建短信签名和模版》小节
            //String[] phones={"+8615899874067", "+8618998995977"};  //发送短信的目标手机号，可填多个。
            sendSmsRequest.setPhoneNumberSet(phones);
            sendSmsRequest.setTemplateID(templateId); //模版id,见《创建短信签名和模版》小节
            //String[] templateParam={"应用离线了", "应用内存溢出，应用down了"};//模版参数，从前往后对应的是模版的{1}、{2}等,见《创建短信签名和模版》小节
            sendSmsRequest.setTemplateParamSet(templateParam);
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey，见《创建secretId和secretKey》小节
            Credential cred = new Credential(secretId, secretKey);
            SmsClient smsClient = new SmsClient(cred, REGION);//第二个ap-chongqing 填产品所在的区
            SendSmsResponse sendSmsResponse= smsClient.SendSms(sendSmsRequest); //发送短信
            //System.out.println("--------"+ JsonUtils.pojoToJson(sendSmsResponse));
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
    }

    //----------------------------------------------------------------阿里云----------------------------------------------------------------
    // https://next.api.aliyun.com/api/Dysmsapi/2017-05-25/SendSms?spm=a2c4g.11186623.2.8.f2682e845Gcyxr&params={}&sdkStyle=old&lang=JAVA
    //https://next.api.aliyun.com/api-tools/demo/Dysmsapi/db7e1211-14e0-4b7b-9011-037dfb85d42e
    //多个手机号用,分割
    public void sendAliyunSms(String phone, String templateCode, String tempeteParam)throws Exception {
        sendAliyunSms(env.getProperty("sms.aliyun.accessKeyId"), env.getProperty("sms.aliyun.accessKeySecret"), env.getProperty("sms.aliyun.signName"), phone, templateCode, tempeteParam);
    }
    public void sendAliyunSms(String accessKeyId, String accessKeySecret, String signName, String phone, String templateCode, String tempeteParam)throws Exception {
        com.aliyun.dysmsapi20170525.Client client = SmsUtil.createClient(accessKeyId, accessKeySecret);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setTemplateParam(tempeteParam);
        //client.sendSms(sendSmsRequest);
        com.aliyun.dysmsapi20170525.models.SendSmsResponse sendResp = client.sendSms(sendSmsRequest);
        String code = sendResp.body.code;
        if (!com.aliyun.teautil.Common.equalString(code, "OK")) {
            //https://www.weimahe.com/5421.html
            log.info("SmsUtil发送短信失败，错误错误信息：{}", sendResp.body.message);
            return ;
        } else {
            log.info("SmsUtil发送短信成功，bizId：{}，requestId: {}", sendResp.body.bizId, sendResp.body.requestId);
        }
    }

    /**
     * 查询发送短信结果（阿里云）
     * @param client
     * @param phoneNumbers
     * @param bizId
     * @param sendDate
     * @throws Exception
     */
    public void querSendResult(com.aliyun.dysmsapi20170525.Client client, String phoneNumbers, String bizId, String sendDate) throws Exception {
        // 2. 等待 10 秒后查询结果
        com.aliyun.teautil.Common.sleep(10000);
        // 3.查询结果
        java.util.List<String> phoneNums = Arrays.stream(phoneNumbers.split(",")).collect(Collectors.toList());
        for (String phoneNum : phoneNums) {
            QuerySendDetailsRequest queryReq = new QuerySendDetailsRequest()
                    .setPhoneNumber(com.aliyun.teautil.Common.assertAsString(phoneNum))
                    .setBizId(bizId)
                    .setSendDate(sendDate) //yyyyMMdd
                    .setPageSize(10L)
                    .setCurrentPage(1L);
            QuerySendDetailsResponse queryResp = client.querySendDetails(queryReq);
            java.util.List<QuerySendDetailsResponseBody.QuerySendDetailsResponseBodySmsSendDetailDTOsSmsSendDetailDTO> dtos = queryResp.body.smsSendDetailDTOs.smsSendDetailDTO;
            // 打印结果
            for (QuerySendDetailsResponseBody.QuerySendDetailsResponseBodySmsSendDetailDTOsSmsSendDetailDTO dto : dtos) {
                if (com.aliyun.teautil.Common.equalString("" + dto.sendStatus + "", "3")) {
                    log.info("" + dto.phoneNum + " 发送成功，接收时间: " + dto.receiveDate + "");
                } else if (com.aliyun.teautil.Common.equalString("" + dto.sendStatus + "", "2")) {
                    log.info("" + dto.phoneNum + " 发送失败");
                } else {
                    log.info("" + dto.phoneNum + " 正在发送中...");
                }
            }
        }
    }
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId) // 您的AccessKey ID
                .setAccessKeySecret(accessKeySecret); // 您的AccessKey Secret
        config.endpoint = "dysmsapi.aliyuncs.com"; // 访问的域名
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public static void main(String[] args) {
//        try {
//            Class<?> ss = Class.forName("com.ruoyi.common.utils.weCat.MessageTemplate");
//            Constructor<?> cc = ss.getConstructor();
//            System.out.println("--------------------------"+cc.newInstance());
//
//            SmsUtil smsUtil = new SmsUtil();
//            JSONObject jo = new JSONObject();
//            //jo.put("orderno", "123456");
//            //jo.put("goodsnum", "3");
//            jo.put("code", "323232");
//            System.out.println("---------" + jo.toJSONString());
//            //smsUtil.sendAliyunSms("LTAI5tJnGyciRyrVxssNAEFZ", "p6ZuvmdEm79A27AdCsjdHLFgP9kQui", "泽熙网络", "13669001897", "SMS_218595036", jo.toJSONString());
//            //smsUtil.sendAliyunSms("LTAI5tJnGyciRyrVxssNAEFZ", "p6ZuvmdEm79A27AdCsjdHLFgP9kQui", "泽熙网络", "13669001897", "SMS_229640703", jo.toJSONString());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        LocalDate today = LocalDate.now();
        for (long i =0L;i <= 11L; i++) {
            LocalDate localDate = today.minusMonths(i);
            String month = localDate.toString().substring(0, 7);
            System.out.println("month:" + month);
        }
    }
}
